package com.itheima.goods.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.goods.pojo.Goods;
import com.itheima.goods.mapper.GoodMapper;
import com.itheima.goods.service.GoodService;
import entity.Result;
import entity.StatusCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class GoodServiceImpl extends ServiceImpl<GoodMapper,Goods> implements GoodService {

    @Override
    public Result findById(Long goodId) {

        Goods goods = this.getById(goodId);

        return new Result(true, StatusCode.OK,null,goods);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result buy(Long goodId, Integer buyNum) {

        Goods goods = this.getById(goodId);
        if (null == goods) {
            return new Result(false, StatusCode.ERROR, "商品不存在，说实话我很奇怪你是怎么找到不存在的商品下单页面的", null);
        }
        Integer num = goods.getNum();
        if (num < buyNum) {
            return new Result(false, StatusCode.ERROR, "商品库存不足，建议去隔壁淘宝", null);
        }
        goods.setNum(num - buyNum);
        if (this.updateById(goods)) {
            return new Result(true, StatusCode.OK, "恭喜你~~~可以下车啦！", null);
        }
        return new Result(false, StatusCode.ERROR, "我很奇怪为什么下单失败，可能是别人的网速比你快吧", null);
    }
}

